package gq.example.aspect;

import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import gq.example.annotation.AutoFill;
import gq.example.context.BaseContext;
import gq.example.enumeration.OperationType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 定义切点
     */
    @Pointcut("execution(* gq.example.mapper.*.*(..))  && @annotation(gq.example.annotation.AutoFill) ")
    public void autoFillPointCut() {}


    /**
     * 方法执行前增强处理
     * @param joinPoint
     */
    @Before("autoFillPointCut()")
    void before(JoinPoint joinPoint) {
        //获取当前数据库操作的类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();

        //获取方法签名的参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object object = args[0];

        //创建要赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long userId  = BaseContext.getCurrentId();

        //根据操作类型动态获取方法类型
        if (operationType == OperationType.INSERT) {
            try{
                //通过反射获取对象的方法
                Method setCreateTime = object.getClass().getMethod("setCreateTime", LocalDateTime.class);
                //Method setCreateUser = object.getClass().getMethod("setCreateUser", Long.class);

                //调用方法
                setCreateTime.invoke(object, now);
                //setCreateUser.invoke(object, userId);

            }catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e){
                e.printStackTrace();
            }
        }
    }
}
